package com.qf.service.impl;

import com.qf.dao.UserDao;
import com.qf.dao.impl.UserDaoImpl;
import com.qf.domain.User;
import com.qf.service.UserService;
import com.qf.utils.EmailUtils;
import com.qf.utils.MD5Utils;

public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();
    @Override
    public boolean checkUserName(String username) {
        User user = userDao.selectByUserName(username);
        if (user!=null){
            return  true;
        }
        return false;
    }

    @Override
    public void register(User user) {
         user.setPassword(MD5Utils.md5(user.getPassword()));
         userDao.insert(user);
         //发送邮件
        EmailUtils.sendEmail(user);
    }

    @Override
    public int active(String email, String code) {
           int result= userDao.updateFlag(email,code);
           return result;
    }

    @Override
    public User login(String username, String password) {
        password=MD5Utils.md5(password);
        User user = userDao.selectByUserName(username);
        if (user==null){
            throw new RuntimeException("用户名不存在");
        }
        if(!user.getPassword().equalsIgnoreCase(password)){
            throw new RuntimeException("密码错误");
        }
        //是否激活
        if(user.getFlag()!=1){
            throw new RuntimeException("账户未激活或激活已过期");
        }
        return user;

    }

    @Override
    public void remove(int id) {
        userDao.delete(id);
    }

    @Override
    public User selectById(Integer uid) {
        return userDao.selectByidName(uid);
    }

    @Override
    public User selectByName(String username) {
        return userDao.selectByname(username);
    }
}
